# -*- coding: utf-8 -*-
# &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
# D7Cl0ud360
# 邮箱: 18656042877@163.com
# 作者：'sugar'
# 公司网址： http://www.dtcloud360.com/
# Copyright 中亿丰信息科技(苏州)有限公司
# 日期：2023/5/25 16:18
# &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
from dtcloud import http
from dtcloud import Command
from dtcloud.addons.rest_controller.handlers import RestController
from ..serializer.role import RoleBodyModel


class RoleRestController(RestController):
    _model = 'dt.role'
    _method_map = {
        'list': 'GET',
        'create': 'POST',
        'update': 'PUT',
        'destroy': 'DELETE',
    }
    _default_auth = 'token'
    _prefix = "/api"
    _type = 'jsonify'
    _fields = ('id', "name", 'users_count', 'seq_no', 'content', 'status', 'users', 'code')
    _order = "seq_no asc"

    def create(self, **data):
        data = RoleBodyModel(**data).dict(exclude_none=True)
        data['users'] = [Command.set(data['users'])]
        role = http.request.env[self._model].sudo().create(data)
        return self.make_response(role.id)

    def update(self, req_id, **data):
        if 'status' in data and len(data) == 1:
            return super().update(req_id, **data)

        data = RoleBodyModel(**data).dict(exclude_none=True)
        data['users'] = [Command.set(data['users'])]
        record = http.request.env[self._model].sudo().browse(int(req_id))
        return self.make_response(record.write(data))

    @http.route('/api/dt_role/permission/<int:role_id>', auth='token', methods=['GET'], type='jsonify')
    def get_permission(self, role_id):
        role = http.request.env['dt.role'].sudo().browse(int(role_id))
        menu_ids = role.menu_ids.filtered(lambda x: x.mtype == 'menu')
        button_list = role.menu_ids.filtered(
            lambda x: x.mtype == 'button'
        )
        return self.make_response({
            "menu_ids": menu_ids.ids,
            "button_list": button_list.ids
        })


class RoleController(http.Controller):
    """
        角色管理
    """
    @http.route('/api/dt_role/options', auth='token', methods=['GET'], type='jsonify')
    def options(self, *args, **kwargs):
        with http.request.env.cr as cursor:
            http.request.env.cr.execute(
                'SELECT "dt_role".id as value, "dt_role".name as label FROM "dt_role" WHERE "dt_role".status = TRUE', [])
            des = [column.name for column in cursor.description]
            # res = http.request.env['dt.role'].sudo().search_read([], fields=['id', 'name'])
            return http.request.make_json_response({
                "status": 0,
                "msg": "请求成功",
                "data": [dict(zip(des, row)) for row in cursor.fetchall()]
            })

    @http.route('/api/dt_role/set_permission/<int:role_id>', auth='token', methods=['POST'], type='jsonify')
    def set_permission(self, role_id, **json_data):
        button_ids = json_data.pop("button_ids", [])
        menu_ids = json_data.pop("menu_ids", [])

        menu_ids.extend(button_ids)
        role_ins = http.request.env['dt.role'].sudo().browse(role_id)

        return http.request.make_json_response({
            "status": 0,
            "msg": "更新成功",
            "data": {
                "flag": role_ins.write({"menu_ids": [Command.set(menu_ids)]})
            }
        })
